package com.aurora.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.aurora.app.entity.Chat;
import com.aurora.app.entity.ChatGroup;
import com.aurora.app.entity.CollectionThing;
import com.aurora.app.entity.CollectionThingStory;
import com.aurora.app.entity.HelpImage;
import com.aurora.app.entity.Message;
import com.aurora.app.entity.PayOrder;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingImage;
import com.aurora.app.entity.ThingStory;
import com.aurora.app.entity.ThingStoryImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.FakeDelete;
import com.aurora.app.enums.PayState;
import com.aurora.app.enums.UtTsType;
import com.aurora.app.exption.NullEntityException;
import com.aurora.app.service.ChatGroupService;
import com.aurora.app.service.ChatService;
import com.aurora.app.service.CollectionThingService;
import com.aurora.app.service.CollectionThingStoryService;
import com.aurora.app.service.HelpImageService;
import com.aurora.app.service.MessageService;
import com.aurora.app.service.PayOrderService;
import com.aurora.app.service.ThingCommentService;
import com.aurora.app.service.ThingImageService;
import com.aurora.app.service.ThingService;
import com.aurora.app.service.ThingStoryCommentService;
import com.aurora.app.service.ThingStoryImageService;
import com.aurora.app.service.ThingStoryService;
import com.aurora.app.service.UserService;
import com.aurora.app.util.DateUtils;
import com.aurora.app.util.StandardResponseBody;
import com.aurora.app.util.WhichLevel;

@Controller
@RequestMapping(value = "api/myself")
public class MyselfController {
	@Resource
	private UserService userService;
	@Resource
	private ThingService thingService;
	@Resource
	private CollectionThingService collectionThingService;
	@Resource
	private CollectionThingStoryService collectionThingStoryService;
	@Resource
	private MessageService messageService;
	@Resource
	private ChatService chatService;
	@Resource
	private ChatGroupService chatGroupService;
	@Resource
	private ThingImageService thingImageService;
	@Resource
	private HelpImageService helpImageService;
	@Resource
	private ThingStoryService thingStoryService;
	@Resource
	private ThingStoryImageService thingStoryImageService;
	@Resource
	private PayOrderService payOrderService;
	@Resource
	private ThingCommentService thingCommentService;
	@Resource
	private ThingStoryCommentService thingStoryCommentService;

	@RequestMapping()
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("myself/myself");
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(user.getNickName());
		mv.addObject("user", user);
		return mv;
	}

	/**
	 * 我的信息
	 * 
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "userInfo")
	public ModelAndView userInfo(HttpServletRequest request, @RequestParam("USERID") String userId) {
		ModelAndView mv = new ModelAndView("myself/userinfo");
		// 用户基本信息
		User user = this.userService.get(userId);
		if (user == null) {
			throw new NullEntityException("找不到实体类");
		}
		// 获取用户发布的闲置
		List<Thing> tList = this.thingService.getListByUserWithPages(request, userId);
		List<String> llist = new ArrayList<String>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (Thing thing : tList) {
				llist.add(this.thingImageService.getFirstImageByThingId(thing.getId()).getPath());
			}
		}
		// 获取成功交易
		mv.addObject("user", user);
		mv.addObject("tList", tList);
		mv.addObject("llist", llist);
		return mv;
	}

	/**
	 * 我的买入
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "myBug")
	public ModelAndView myBug(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		ModelAndView mv = new ModelAndView("myself/mybug");
		mv.addObject("user", user);
		return mv;
	}

	/**
	 * 我的发布
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "myPublish")
	public ModelAndView myPublish(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		ModelAndView mv = new ModelAndView("myself/mypublish");
		mv.addObject("user", user);
		return mv;
	}

	/**
	 * 我的喜爱
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "myLike")
	public ModelAndView myLike(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		ModelAndView mv = new ModelAndView("myself/myLike");
		List<CollectionThing> cList = this.collectionThingService.getListByUserWithPages(request, user.getId());
		List<String> timeList = new ArrayList<String>();
		List<Integer> levelList = new ArrayList<Integer>();
		if (cList != null && !cList.isEmpty()) {
			for (CollectionThing ct : cList) {
				timeList.add(DateUtils.getMyFormatTime(ct.getThing().getCreateTime()));
				levelList.add(WhichLevel.getLevel(ct.getThing().getUser().getHuoyueIntegral(),
						ct.getThing().getUser().getJiaoyiIntegral()).ordinal());
			}
		}
		mv.addObject("cList", cList);
		mv.addObject("timeList", timeList);
		return mv;
	}

	/**
	 * 我的消息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "myNews")
	public ModelAndView myNews(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("myself/mynews");
		return mv;
	}

	/**
	 * 我的卖出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mySell")
	public ModelAndView mySell(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("myself/mysell");
		return mv;
	}

	/**
	 * 获取未读消息数目
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getMessageNotReadCount")
	@ResponseBody
	public String getMessageNotReadCount(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		Long count = this.messageService.getUserMessageCountNotRead(user.getId());
		modelMap.put("COUNT", count);
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取未读消息列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getMessageList")
	@ResponseBody
	public String getMessageList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<Message> mList = this.messageService.getUserMessageList(user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (mList != null && !mList.isEmpty()) {
			List<String> msgIds = new ArrayList<String>();
			for (Message msg : mList) {
				msgIds.add(msg.getId());
				Map<String, Object> map = new HashMap<String, Object>();
				JSONObject jsonObj;
				Chat chat = null;
				try {
					jsonObj = new JSONObject(msg.getTip());
					chat = this.chatService.getLastChatByGroupId(jsonObj.getString("CHATGROUP"));
					ChatGroup chatGroup = this.chatGroupService.get(jsonObj.getString("CHATGROUP"));
					if (chat == null) {
						throw new JSONException("找不到聊天记录");
					}
					if (chatGroup == null) {
						throw new JSONException("找不到聊天组");
					}
					map.put("USERIMG", msg.getUser().getHeadimgurl());
					map.put("USERNICKNAME", msg.getUser().getNickName());
					if (chatGroup.getUtTsType().equals(UtTsType.UserThing)) {
						ThingImage thingImage = this.thingImageService
								.getFirstImageByThingId(chatGroup.getThing().getId());
						if (thingImage == null) {
							throw new JSONException("找不到图片");
						}
						map.put("THINGIMG", thingImage.getPath());
					} else if (chatGroup.getUtTsType().equals(UtTsType.Help)) {
						HelpImage helpImage = this.helpImageService.getFirstImageByHelpId(chatGroup.getHelp().getId());
						if (helpImage == null) {
							map.put("THINGIMG", "images/help_image.png");
						} else {
							map.put("THINGIMG", helpImage.getPath());
						}

					} else if (chatGroup.getUtTsType().equals(UtTsType.ThingStory)) {
						ThingStoryImage stroyImage = this.thingStoryImageService
								.getFirstImageByStoryThingId(chatGroup.getThingStory().getId());
						if (stroyImage == null) {
							map.put("THINGIMG", "images/story_image.png");
						} else {
							map.put("THINGIMG", stroyImage.getPath());
						}

					}
				} catch (JSONException e) {
					return StandardResponseBody.Default(0, e.getMessage(), null);
				}
				map.put("MSG", chat.getMessage());
				map.put("TIME", DateUtils.getMyFormatTime(chat.getCreateTime()));
				map.put("URL", msg.getUrl());
				resultList.add(map);
			}
			this.messageService.readMessage(msgIds.toArray());
		}
		System.out.println(JSON.toJSONString(resultList));
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取我的发布，闲置物品
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getMyPublishThingList")
	@ResponseBody
	public String getMyPublishThingList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<Thing> tList = this.thingService.getListByUserWithPages(request, user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (Thing thing : tList) {
				Map<String, Object> map = new HashMap<String, Object>();
				System.out.println(thing.getTitle());
				map.put("TITLE", thing.getTitle());
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
				df.format(thing.getCost());
				map.put("COST", "￥" + df.format(thing.getCost()));
				map.put("ORIGINCOST", "￥" + df.format(thing.getOriginalCost()));
				List<ThingImage> imgList = this.thingImageService.getBeforeImageByThingId(thing.getId(), 3);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					for (ThingImage thingImg : imgList) {
						imgs += thingImg.getPath() + ",";
					}
					imgs = imgs.substring(0, imgs.length() - 1);
				}
				map.put("LIKE", thing.getZan());
				map.put("COMMENTNUM", thingCommentService.getCommentNum(thing));
				map.put("IMGS", imgs);
				map.put("TIME", DateUtils.getShowLastTime(thing.getOutOfTime()));
				map.put("THINGID", thing.getId());
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取我的发布，物语
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getMyPublishThingStoryList")
	@ResponseBody
	public String getMyPublishThingStoryList(HttpServletRequest request, int pageNum, int pageSize) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//User user = (User) request.getSession().getAttribute("user");
		List<ThingStory> tList = this.thingStoryService.getListByPages((pageNum - 1) * pageSize, pageSize);
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (ThingStory thingStory : tList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TITLE", thingStory.getTitle());
				map.put("TOPIC", thingStory.getStoryTopic().getName());
				List<ThingStoryImage> imgList = this.thingStoryImageService
						.getBeforeImageByStoryThingId(thingStory.getId(), 3);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					for (ThingStoryImage thingImg : imgList) {
						imgs += thingImg.getPath() + ",";
					}
					imgs = imgs.substring(0, imgs.length() - 1);
				}
				map.put("IMGS", imgs);
				map.put("LIKE", thingStory.getZan());
				map.put("COMMENTNUM", thingStoryCommentService.getCommentNum(thingStory));
				map.put("THINGSTORYID", thingStory.getId());
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取我的卖出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getSellThingList")
	@ResponseBody
	public String getSellThingList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<PayOrder> pList = this.payOrderService.getSellByUserWithPages(request, user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(pList)) {
			for (PayOrder payOrder : pList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TITLE", payOrder.getThing().getTitle());
				map.put("THINGID", payOrder.getThing().getId());
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
				map.put("COST", "￥" + df.format(payOrder.getThing().getCost()));
				List<ThingImage> imgList = this.thingImageService.getBeforeImageByThingId(payOrder.getThing().getId(),
						1);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					imgs = imgList.get(0).getPath();
				}
				map.put("IMGS", imgs);
				map.put("CHATGROUPID", chatGroupService.getChatGroup(payOrder.getThing(), null, null, user, UtTsType.UserThing).getId());
				map.put("THINGID", payOrder.getThing().getId());
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取我的买入
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getBugThingList")
	@ResponseBody
	public String getBugThingList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<PayOrder> pList = this.payOrderService.getBugByUserWithPages(request, user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(pList)) {
			for (PayOrder payOrder : pList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TITLE", payOrder.getThing().getTitle());
				map.put("THINGID", payOrder.getThing().getId());
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
				map.put("COST", "￥" + df.format(payOrder.getThing().getCost()));
				List<ThingImage> imgList = this.thingImageService.getBeforeImageByThingId(payOrder.getThing().getId(),
						1);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					imgs = imgList.get(0).getPath();
				}
				map.put("IMGS", imgs);
				map.put("THINGID", payOrder.getThing().getId());
				map.put("CHATGROUPID", chatGroupService.getChatGroup(payOrder.getThing(), null, null, user, UtTsType.UserThing).getId());
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 物品已出售
	 * 
	 * @param request
	 * @param thing
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/haveSell")
	@ResponseBody
	public String haveSell(HttpServletRequest request, Thing thing, String bugUserId) {
		PayOrder payOrder = this.payOrderService.getByThing(thing.getId());
		User user = this.userService.get(bugUserId);

		if (payOrder == null) {
			return StandardResponseBody.Default(0, "无法获取订单", null);
		} else if (user == null) {
			return StandardResponseBody.Default(0, "购买用户不存在", null);
		} else {
			payOrder.setState(PayState.SUCCESS);
			payOrder.setUser(user);
			this.payOrderService.save(payOrder);
			return StandardResponseBody.Default(1, "", null);
		}
	}

	/**
	 * 物品取消发布
	 * 
	 * @param request
	 * @param thing
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/thingCancel")
	@ResponseBody
	public String thingCancel(HttpServletRequest request, Thing thing) {
		Thing t = this.thingService.get(thing.getId());
		if (t == null) {
			return StandardResponseBody.Default(0, "该闲置不存咋", null);
		} else {
			t.setIsDelete(FakeDelete.ISDELETE);
			this.thingService.update(t);
			return StandardResponseBody.Default(1, "", null);
		}

	}

	/**
	 * 获取可能的购买人
	 * 
	 * @param request
	 * @param thing
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getMaybeBugUser")
	@ResponseBody
	public String getMaybeBugUser(HttpServletRequest request, Thing thing) {
		List<ChatGroup> cList = this.chatGroupService.getListByThing(thing);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (!CollectionUtils.isEmpty(cList)) {
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
			for (ChatGroup c : cList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("USERID", c.getUser().getId());
				map.put("NICKNAME", c.getUser().getNickName());
				resultList.add(map);
			}
			modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
			return StandardResponseBody.Default(1, "", modelMap);
		}
		return StandardResponseBody.Default(0, "没有找到此闲置相关的聊天信息", null);
	}

	/**
	 * 获取我的闲置收藏
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getCollectionThingThingList")
	@ResponseBody
	public String getCollectionThingThingList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<CollectionThing> tList = this.collectionThingService.getListByUserWithPages(request, user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (CollectionThing thing : tList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TITLE", thing.getThing().getTitle());
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
				map.put("COST", "￥" + df.format(thing.getThing().getCost()));
				map.put("ORIGINCOST", "￥" + df.format(thing.getThing().getOriginalCost()));
				List<ThingImage> imgList = this.thingImageService.getBeforeImageByThingId(thing.getThing().getId(), 3);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					for (ThingImage thingImg : imgList) {
						imgs += thingImg.getPath() + ",";
					}
					imgs = imgs.substring(0, imgs.length() - 1);
				}
				map.put("IMGS", imgs);
				map.put("THINGID", thing.getThing().getId());
				map.put("USERID", thing.getThing().getUser().getId());
				map.put("USERIMG", thing.getThing().getUser().getHeadimgurl());
				map.put("NICKNAME", thing.getThing().getUser().getNickName());
				map.put("TIME", DateUtils.getMyFormatTime(thing.getThing().getCreateTime()));
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}

	/**
	 * 获取我的故事收藏
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "/getCollectionStoryThingList")
	@ResponseBody
	public String getCollectionStoryThingList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<CollectionThingStory> tList = this.collectionThingStoryService.getListByUserWithPages(request,
				user.getId());
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (CollectionThingStory thing : tList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TITLE", thing.getThingStory().getTitle());
				List<ThingStoryImage> imgList = this.thingStoryImageService
						.getBeforeImageByStoryThingId(thing.getThingStory().getId(), 3);
				String imgs = "";
				if (!CollectionUtils.isEmpty(imgList)) {
					for (ThingStoryImage thingImg : imgList) {
						imgs += thingImg.getPath() + ",";
					}
					imgs = imgs.substring(0, imgs.length() - 1);
				}
				map.put("IMGS", imgs);
				map.put("STORYID", thing.getThingStory().getId());
				map.put("USERID", thing.getThingStory().getUser().getId());
				map.put("USERIMG", thing.getThingStory().getUser().getHeadimgurl());
				map.put("NICKNAME", thing.getThingStory().getUser().getNickName());
				resultList.add(map);
			}
		}
		modelMap.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.Default(1, "", modelMap);
	}
}
